package com.zzg.test2.manager;

import android.app.Activity;
import android.content.Context;
import android.webkit.WebView;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class CacheWebLoadManager {
    private final static CacheWebLoadManager instance = new CacheWebLoadManager();
    private DiskCacheManager diskCacheManager;

    private CacheWebLoadManager() {
        // 初始化线程池
        executorService = Executors.newFixedThreadPool(3);
    }

    public static CacheWebLoadManager getInstance() {
        return instance;
    }

    private ExecutorService executorService;
    private Map<String, Boolean> downloadingUrls = new HashMap<>();

    // 获取缓存文件
    public File getCachedFile(Context context, String url) {
        String filename = String.valueOf(url.hashCode());


        return new File(context.getExternalCacheDir(), filename);
//        return new File(context.getCacheDir(), filename);
    }

    // 检查URL是否正在下载
    public synchronized boolean isDownloading(String url) {
        return downloadingUrls.containsKey(url) && downloadingUrls.get(url);
    }

    // 设置URL下载状态
    public synchronized void setDownloading(String url, boolean downloading) {
        downloadingUrls.put(url, downloading);
    }

    // 异步下载并缓存资源
    public void downloadAndCacheAsync(final Context context, final WebView webView, final String url) {
        executorService.execute(() -> {
            try {
                URL downloadUrl = new URL(url);
                HttpURLConnection connection = (HttpURLConnection) downloadUrl.openConnection();
                connection.connect();

                if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
                    InputStream inputStream = connection.getInputStream();

                    // 读取数据
                    byte[] buffer = new byte[1024];
                    int bytesRead;
                    StringBuilder content = new StringBuilder();

                    while ((bytesRead = inputStream.read(buffer)) != -1) {
                        content.append(new String(buffer, 0, bytesRead));
                    }
                    inputStream.close();

                    // 保存到缓存
                    File cachedFile = getCachedFile(context,url);
                    try (FileOutputStream fos = new FileOutputStream(cachedFile)) {
                        fos.write(content.toString().getBytes());
                    }

                    // 刷新WebView，使缓存生效
                    ( (Activity) context).runOnUiThread(() -> webView.reload());
                }

                connection.disconnect();
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                setDownloading(url, false);
            }
        });
    }

    // 清除缓存
    public void clearCache(Context context) {

//        File cacheDir = context.getCacheDir();
        File cacheDir = context.getExternalCacheDir();
        if (cacheDir != null && cacheDir.isDirectory()) {
            for (File file : cacheDir.listFiles()) {
                file.delete();
            }
        }
        downloadingUrls.clear();
    }


}
